package com.weilive.core.session;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.weilive.core.netty.http.HttpServlet;
import com.weilive.core.utils.QueryStringDecoder;
import com.weilive.core.utils.UuidUtils;

public class SessionService {
	private static final Logger logger = LoggerFactory.getLogger(SessionService.class);
	private static final Map<String, SessionAccount> NATIVE_SESSION = new ConcurrentHashMap<String, SessionAccount>();
	private static final Map<Long, String> NATIVE_SESSION_ROLE = new ConcurrentHashMap<Long, String>();

	public static SessionAccount getSession(String gsessionId) {
		if (StringUtils.isEmpty(gsessionId)) {
			logger.warn("gsessionId为空!");
			return null;
		}
		SessionAccount sa = NATIVE_SESSION.get(gsessionId);
		if (sa == null) {
			if (sa == null) {
				logger.warn("登陆已过期，请重新登录!");
				return null;
			}
		}
		return sa;
	}

	public static SessionAccount getSession(HttpRequest req) throws Exception {
		QueryStringDecoder decoder = HttpServlet.decodeQueryString(req);
		String gsessionId = decoder.get("gsessionId");
		if (StringUtils.isEmpty(gsessionId)) {
			return null;
		}

		SessionAccount sa = NATIVE_SESSION.get(gsessionId);
		if (sa == null) {
			if (sa == null) {
				logger.warn("登陆已过期，请重新登录!");
				return null;
			}
		}
		return sa;
	}

	public static String newSession(SessionAccount acct) {
		String gsessionId = UuidUtils.randomUUID().replace("-", "").toLowerCase();
		acct.setSessionId(gsessionId);
		removeSession(acct.getUserId());
		NATIVE_SESSION.put(gsessionId, acct);
		NATIVE_SESSION_ROLE.put(acct.getUserId(), gsessionId);
		return gsessionId;
	}

	public static void removeSession(Long roleId) {
		String oldgsessionid = NATIVE_SESSION_ROLE.remove(roleId);
		if (null != oldgsessionid) {
			NATIVE_SESSION.remove(oldgsessionid);
		}
	}
}
